package com.distributed.netty.client;


import com.distributed.netty.entity.ElementJob;
import com.rcache.core.cache.Rcache;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.HashedWheelTimer;
import org.apache.log4j.Logger;

import java.util.LinkedList;

/**
 * @desc	客户端	
 * @author	高增源
 * @time	2021年11月18日
 */
public class Client extends Thread{
	private Rcache cache;
	private final LinkedList<ElementJob> jobList=new LinkedList<>();
	public Client(Rcache cache,String ip) {
		this.cache = cache;
		this.ip=ip;
	}
	Logger LOG=Logger.getLogger(Client.class);

	private String ip;

	/**
	 * @desc 添加任务
	 * @param elementJob
	 */
	public void addJob(ElementJob elementJob) {
		jobList.add(elementJob);
	}
	public void connect() throws InterruptedException {
		LOG.debug("客户端正在启动...");
		HashedWheelTimer timer = new HashedWheelTimer();
		Bootstrap bootstrap =new Bootstrap();
		EventLoopGroup work=new NioEventLoopGroup();
		bootstrap.group(work).channel(NioSocketChannel.class)
				.handler(new HeartBeatClientInitializer(bootstrap, timer,true,cache,jobList));
//				.handler(new ChatHandler(cache,jobList))
		//同步的开
		ChannelFuture con;
		if (ip!=null){
			con = bootstrap.connect(ip,cache.getDistributePort()).sync();
		}else{
			con = bootstrap.connect(cache.getDistributeIP(),cache.getDistributePort()).sync();
		}
		LOG.debug("客户端连接成功了");
		con.channel().closeFuture().sync();
//		work.shutdownGracefully();
	}



	@Override
	public void run() {
		LOG.debug("slave线程已启动……");
		try {
			connect();
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}

	public Rcache getCache() {
		return cache;
	}

	public void setCache(Rcache cache) {
		this.cache = cache;
	}

}
